package com.example.esp8266.TcpService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.dlong.dl10netassistant.OnNetThreadListener;
import com.dlong.dl10netassistant.TcpClientThread;
import com.example.esp8266.Library.PermissionRequest.NotificationHelper;
import com.example.esp8266.R;

public class Tcp_Connect extends Service implements OnNetThreadListener {
    private TcpClientThread tcp;
    private static final String CHANNEL_ID = "ForegroundServiceChannel";
    private PowerManager.WakeLock wakeLock;
    private ScheduledExecutorService scheduler;

    @Override
    public void onCreate() {
        super.onCreate();

        // 创建并获取唤醒锁
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ESP8266_APP::TcpWakelock");
        wakeLock.acquire();

        // 检查并请求通知权限
        if (!NotificationHelper.checkNotificationPermission(this)) {
            NotificationHelper.requestNotificationPermission(this);
            return;
        }

        // 创建通知通道
        NotificationHelper.createNotificationChannel(this);

        // 创建前台通知
        Notification notification = NotificationHelper.createNotificationBuilder(this, "服务正在运行", "自动控制服务正在维护TCP连接").build();
        startForeground(1, notification);

        // 初始化TCP连接
        tcp = new TcpClientThread("192.168.12.114", 8899);
        tcp.start();
        tcp.setThreadListener(this); // 设置回调监听器

        // 使用 ScheduledExecutorService 来计划重连任务
        scheduler = Executors.newScheduledThreadPool(1);
        startTCPConnection();
    }

    private void startTCPConnection() {
        scheduler.scheduleWithFixedDelay(() -> {
            try {
                if (!tcp.isConnected()) {
                    updateNotification("连接中", "正在尝试建立连接...");
                    tcp.start();
                }
            } catch (Exception e) {
                updateNotification("连接失败", "尝试重新连接中...");
                e.printStackTrace();
            }
        }, 0, 5, TimeUnit.SECONDS);
    }

    // 发送数据方法
    public void sendData(String data) {
        try {
            if (tcp.isConnected()) {
                tcp.send(data.getBytes());
            }
        } catch (Exception e) {
            updateNotification("发送失败", "未连接设备...");
        }
    }

    @Override
    public void onAcceptSocket(@NonNull String s) {}

    @Override
    public void onConnected(@NonNull String s) {
        updateNotification("连接成功", "TCP连接已成功建立");
    }

    @Override
    public void onConnectFailed(@NonNull String s) {
        updateNotification("连接失败", "无法建立TCP连接");
    }

    @Override
    public void onDisconnect(@NonNull String s) {
        updateNotification("连接断开", "TCP连接已断开");
    }

    @Override
    public void onError(@NonNull String s, @NonNull String s1) {
        updateNotification("错误", "发生错误: " + s1);
    }

    @Override
    public void onReceive(@NonNull String s, int i, long l, @NonNull byte[] bytes) {
        final String receivedData = new String(bytes);
        updateNotification("收到数据", "内容: " + receivedData);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (tcp != null) {
            tcp.close();
        }
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
        if (scheduler != null) {
            scheduler.shutdown();
        }
    }

    // 定义 Binder
    public class TcpBinder extends Binder {
        public Tcp_Connect getService() {
            return Tcp_Connect.this;
        }
    }

    private final IBinder binder = new TcpBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    private Notification createNotification(String title, String content) {
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(R.drawable.run_icon)
                .build();
    }

    public void updateNotification(String title, String content) {
        Notification notification = createNotification(title, content);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);
    }
}